package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import java.util.concurrent.TimeUnit;

import android.app.Dialog;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Page;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IPage;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.PageAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2017/7/13 14:26
 * 邮箱：zhanghuaiha@gmail.com
 */

public class PagePresenter extends BasePresenter<IPage> {

    private String versionCode;
    private String id;
    private String udid;
    private PageAdapter pageAdapter;
    private RecyclerView rv;
    private LinearLayoutManager linearLayoutManager;
    private int total = 30;
    private int num = 1;
    private String type0,type1,type2,type3,type4;
    private SwipeRefreshLayout srl;
    private TextView tv;
    private boolean refreshing;
    private Dialog dialog;

    public PagePresenter(BaseActivity context) {
        super(context);
    }


    public void loadContacts(){
        versionCode = ObtainVersion.getVersionName(mContext);
        id = App.SP.getString("id", "");
        udid = App.SP.getString("udid", "");
        rv = getView().getRv();
        srl = getView().getSrl();
        tv = getView().getTV();
        linearLayoutManager = new LinearLayoutManager(mContext);
        rv.setLayoutManager(linearLayoutManager);
        setAdapter();
        srl.setColorSchemeResources(R.color.title_bg,R.color.blue);
        srl.setOnRefreshListener(() -> {
            num = 0;
            refreshing = srl.isRefreshing();
            loadNetWork(num+"",type0,type1,type2,type3,type4);

        });
    }

    private void setAdapter() {
        if (pageAdapter == null) {
            pageAdapter = new PageAdapter(mContext);
        }
        rv.setAdapter(pageAdapter);

        //加载更多
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                    if (lastVisiblePosition >= linearLayoutManager.getItemCount() - 1) {
                        if (total < 20) {
                            return;
                        }else {
                            loadNetWork(num+"",type0,type1,type2,type3,type4);
                            num++;
                        }
                    }
                }
            }
        });

        pageAdapter.setItemClickListenter((dataBean, position) -> {
            detection(dataBean.getAlias());
//            ToastUtil.showToast(position+"");
        });


    }
    //判断排序
    public void setType(String type0,String type1,String type2,String type3,String type4){
        num = 0;
        this.type0 = type0;
        this.type1 = type1;
        this.type2 = type2;
        this.type3 = type3;
        this.type4 = type4;
        loadNetWork(num+"",type0,type1,type2,type3,type4);

    }

    //加载默认数据
    public void loadNetWork(String num,String type0,String type1,String type2,String type3,String type4) {
        uploadDialog();
        //device_type  1 只看 WiFi 4只看密码
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.PAGE);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("page_size","15");
        map.put("page_index",num);

        if (!type1.equals("-1")) {
            map.put("on_line",type1);
        }
        if (!type2.equals("-1")) {
            if (type2.equals("asc") || type2.equals("desc")) {
                map.put("electricity_sc_status",type2);
            }else {
                map.put("dump_energy_per",type2);
            }
        }
        if (!type3.equals("-1")) {
            map.put("offline_day",type3);
        }

        if (!type4.equals("-1")) {
            map.put("device_type",type4);
        }

        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getPage(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<Page>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<Page>> listBaseResponseEntity) {
                        tv.setText(listBaseResponseEntity.total);
                        if (listBaseResponseEntity.code == 200) {
                            if (num.equals("0")) {
                                total = Integer.parseInt(listBaseResponseEntity.total);
                                List<Page> data = listBaseResponseEntity.data;
                                if (data.size() == 0) {
                                    rv.setVisibility(View.GONE);
                                }else{
                                    rv.setVisibility(View.VISIBLE);
                                }
                                pageAdapter.addData(data);
                            }else {
                                total = Integer.parseInt(listBaseResponseEntity.total);
                                List<Page> data = listBaseResponseEntity.data;
                                pageAdapter.addLastData(data);
                            }
                        }else {
                            DialogUtils.TSDialog(mContext,listBaseResponseEntity.message,true);
                        }
                        dialog.dismiss();
                        if(refreshing) srl.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        DialogUtils.TSDialog(mContext,mContext.getString(R.string.error_date),true);
                        dialog.dismiss();
                        if(refreshing) srl.setRefreshing(false);
                    }
                });
    }

    //指令：检查状态（在线）
    public void detection(String alias){
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.PAGE);
        map.put("udid",udid);
        map.put("alias",alias);
        map.put("eid",id);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getcheck_status(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                        if (stringBaseResponseEntity.code == 200) {
                            Observable.timer(2, TimeUnit.SECONDS).subscribe(aLong -> {
                                String data = stringBaseResponseEntity.data;
                                message_status(data);
                            });
                        }else {
                            DialogUtils.TSDialog(mContext,stringBaseResponseEntity.message,true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        DialogUtils.TSDialog(mContext,mContext.getString(R.string.error_date),true);
                    }
                });

    }

    //查询消息是否已到达设备
    public void message_status(String message_id){
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.PAGE);
        map.put("udid",udid);
        map.put("message_id",message_id);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getMessage(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                        if (stringBaseResponseEntity.code == 200) {
                           //该设备当前实时在线
                            DialogUtils.TSDialog(mContext,mContext.getString(R.string.success_online),true);
                        }else {
                            DialogUtils.TSDialog(mContext,stringBaseResponseEntity.message,true);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        DialogUtils.TSDialog(mContext,mContext.getString(R.string.error_date),true);
                    }
                });
    }

    public void uploadDialog(){
        dialog = DialogUtils.uploadDialog(mContext, mContext.getString(R.string.upload), true);
    }
}
